package com.cmw.auntapp.ui;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.cmw.auntapp.R;
import com.cmw.auntapp.component.FileChoosePopWindow;
import com.cmw.auntapp.component.SendCountDownTimer;
import com.cmw.auntapp.constant.CommandType;
import com.cmw.auntapp.constant.Constant;
import com.cmw.auntapp.core.base.vo.DataResult;
import com.cmw.auntapp.core.util.AppTools;
import com.cmw.auntapp.core.util.BitmapUtil;
import com.cmw.auntapp.core.util.FastJsonUtil;
import com.cmw.auntapp.core.util.SharedPreferencesUtil;
import com.cmw.auntapp.core.util.StringHandler;
import com.cmw.auntapp.core.util.ToastAlert;
import com.cmw.auntapp.listener.BackListener;
import com.cmw.auntapp.model.MemberModel;
import com.cmw.auntapp.presenter.LoginPresenter;
import com.cmw.auntapp.presenter.MainPresenter;
import com.cmw.auntapp.presenter.SysBasePresenter;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.RequiresApi;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

import static com.cmw.auntapp.R2.id.tv_account;
import static com.cmw.auntapp.R2.id.tv_agreement;
import static com.cmw.auntapp.R2.id.tv_clean;
import static com.cmw.auntapp.R2.id.tv_order;
import static com.cmw.auntapp.R2.id.tv_reward;
import static com.cmw.auntapp.R2.id.tv_settle;
import static com.cmw.auntapp.constant.Constant.ATTACHMENT_FORMTYPE_51;
import static com.cmw.auntapp.constant.Constant.ATTACHMENT_FORMTYPE_52;
import static com.cmw.auntapp.constant.Constant.ATTACHMENT_FORMTYPE_53;
import static com.cmw.auntapp.constant.Constant.ATTACHMENT_FORM_TYPE_20;
import static com.cmw.auntapp.constant.Constant.USER_MEMBERID_KEY;
import static com.cmw.auntapp.core.util.ToastAlert.ACTIONBTN_OK;

/**
 *  用户中心
 *  @auth chengmingwei
 *  @date 2021/4/18 16:14
 *  @contanct 13922111489/340360491@qq.com
 */
public class UserCenterActivity extends BaseActivity {


    @BindView(R.id.iv_my)
    ImageView ivMy;

    @BindView(R.id.tv_my_account)
    TextView tvMyAccount;

    @BindView(R.id.btn_curr_version)
    Button btnCurrVersion;

    private FileChoosePopWindow pop;

    private ProgressDialog progressDialog; // 上传进度条

    private boolean isLoadData = true;

    private LoginPresenter loginPresenter;

    SysBasePresenter sysBasePresenter;

    MainPresenter mainPresenter;

    private MemberModel currMember;

    @Override
    protected int getActivityLayout() {
        return R.layout.activity_user_center;
    }

    @Override
    void onInit(Bundle savedInstanceState) {
        setTitle(R.string.user_center_title);
        loginPresenter = new LoginPresenter(this);
        sysBasePresenter = new SysBasePresenter(this);
        mainPresenter = new MainPresenter(this);
        loadData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG, "onResume...");
    }

    private void loadData() {
        String versionName = AppTools.getVerName(getBaseContext());
        String versionInfo = StringHandler.formatStr(getString(R.string.app_version_info), versionName);
        btnCurrVersion.setText(versionInfo);
        loginPresenter.getMemberInfo();
    }

    @Override
    protected BackListener getCustBackListener() {
        return new BackListener() {
            @Override
            public void execute(View view) {
                if (null != Constant.userCenterBackActivity) {
                    Intent intent = new Intent(UserCenterActivity.this, Constant.userCenterBackActivity);
                    startActivity(intent);
                } else {
                    gotoBack();
                }
            }
        };
    }

    /**
     * 图片选择 修改会员图像
     * @param view
     */
    @OnClick(R.id.iv_my)
    @RequiresApi(api = Build.VERSION_CODES.N)
    public void editMyPhoto(View view) {
        int viewId = view.getId();
        if (null == pop) pop = new FileChoosePopWindow(this);
        pop.setSourceViewId(view.getId());
        pop.showPopup();
    }


    @OnClick(R.id.tv_my_info)
    public void viewMyInfo(View view) {
        go(UserEditActivity.class);
    }

    /**
     * 功能点击事件
     * @param view
     */
    @OnClick({R.id.tv_order, R.id.tv_account, R.id.tv_settle,
    R.id.tv_reward,R.id.tv_clean,R.id.tv_agreement})
    public void doFunClick(View view){
        int viewId = view.getId();
        switch (viewId) {
            case tv_order:{ // 订单列表
                go(OrderListActivity.class);
                break;
            } case tv_account : { // 账号管理
                doGoUserDetail(view);
                break;
            } case tv_settle : { // 每日结算
                go(DaySettleActivity.class);
                break;
            } default:{
                //ToastAlert.showMsg("你所点击的功能即将开发，敬请期待!");
                viewAgreement(view);
            }
        }
    }

    /**
     * 我的 -> 跳转到账号管理
     */
    public void doGoUserDetail(View view){
        boolean isLogin = mainPresenter.isLogin();
        if (!isLogin) {
            go(LoginActivity.class);
            return;
        }
        go(UserDetailActivity.class);
    }

    /**
     * 查看用户协议
     * @param view
     */
    public void viewAgreement(View view){
        int viewId = view.getId();
        int formType = -1;
        switch (viewId) {
            case tv_reward:{ // 奖励说明(APP)
                formType = ATTACHMENT_FORMTYPE_52;
                break;
            }  case tv_clean:{  // 清洁标准工具包说明(APP)
                formType = ATTACHMENT_FORMTYPE_53;
                break;
            }  case tv_agreement:{  // 合作协议(APP)
                formType = ATTACHMENT_FORMTYPE_51;
                break;
            }
        }
        Map<String, String> params = new HashMap<>();
        params.put("formType", formType+"");
        go(HtmlContentActivity.class, params);
    }


    /**
     * 联系客服
     * @param view
     */
    @OnClick(R.id.btn_call_service_tel)
    public void doCallTel(View view) {
        Log.w(TAG,"doCallTel . 打电话...");
        checkPermissionRequest();
    }

    public void checkPermissionRequest() {
        RxPermissions permissions = new RxPermissions(this);
        permissions.setLogging(true);
        permissions.request(Manifest.permission.CALL_PHONE).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                Log.e(TAG, "找打电话权限申请："+(aBoolean ? "成功" : "失败"));
                String phoneNum = getResources().getString(R.string.common_company_tel);
                phoneNum = phoneNum.replace("-", "");
                Intent intent = new Intent(Intent.ACTION_CALL);
                Uri data = Uri.parse("tel:" + phoneNum);
                intent.setData(data);
                startActivity(intent);
            }
        });
    }
    /**
     * 退出退登
     * @param view
     */
    @OnClick(R.id.btn_logout)
    public void logout(View view) {
        ToastAlert.confirm(this, "退出登录提示","确定要退出登录吗？", (String actionBtn)->{
            if (!ACTIONBTN_OK.equals(actionBtn)) {
                return;
            }
            loginPresenter.logout();
        });
    }

    @Override
    public boolean doSuccess(CommandType commandType, DataResult dataResult) {
        switch (commandType) {
            case USER_LOGOUT:{ //跳转到指定页面
                ToastAlert.showMsg("退出成功，感谢您的使用!");
                go(MainActivity.class);
                break;
            }case GET_DETAIL:{ // 加载用户信息
                JSONObject dataJson = (JSONObject)dataResult.getDatas();
                MemberModel memberModel = FastJsonUtil.convertJsonToObj(dataJson.getJSONObject("map"), MemberModel.class);
                setValues(memberModel);
                break;
            }case UPLOAD:{ // 文件上传
                Object datas = dataResult.getDatas();
                Log.i(TAG, "附件数据.datas = "+datas.toString());
                JSONObject resultData =  (JSONObject)datas;
                setAttachmentIdToView(resultData);
                break;
            }
        }
        return true;
    }

    private void setAttachmentIdToView(JSONObject resultData) {
        View imageView = pop.getSelectView();
        if (imageView == null) {
            Toast.makeText(this, "找不到上传的图片对象，无法绑定附件ID", Toast.LENGTH_LONG).show();
            return;
        }
        Long attachmentId = resultData.getLong("attachmentId");
        String filePath = resultData.getString("filePath");
        ivMy.setTag(attachmentId.toString());
        Map<String, String> params = new HashMap<>();
        params.put("imgPath", filePath);
        loginPresenter.editMemberInfo(params); //更新会员图像
    }

    public void setValues(MemberModel memberModel) {
        currMember = memberModel;
        String account = memberModel.getAccount();
        String rname = memberModel.getRname();
        String imgPath = memberModel.getImgPath();
        if (TextUtils.isEmpty(rname)) {
            rname = account;
        }
        tvMyAccount.setText(rname);
        if (!TextUtils.isEmpty(imgPath)) {
            BitmapUtil.getBtimapUtil(this).setDrawableByNetWork(ivMy, imgPath);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        isLoadData = false;
        super.onActivityResult(requestCode, resultCode, data);
        List<LocalMedia> images;
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调

                    images = PictureSelector.obtainMultipleResult(data);
                    doUpload(images);

//                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    break;
            }
        }
    }

    public void doUpload(List<LocalMedia> images) {
        if (null == images || images.isEmpty()) {
            Toast.makeText(this, "请选择要上传的图片", Toast.LENGTH_LONG).show();
            return;
        }
        String imagePath = images.get(0).getPath();
        File file = new File(imagePath);
        Bitmap imgae = BitmapUtil.getBtimapUtil(this).fileToBitmap(imagePath);
        ivMy.setImageBitmap(imgae);
        ivMy.setTag("0"); //代表已经选择了图片
        pop.setSelectView(ivMy);


        Map<String,String> params = new HashMap<>();
        params.put("formType", ATTACHMENT_FORM_TYPE_20+"");
        Long formId = null;
        if (currMember != null) {
            formId = currMember.getId();
        } else {
            SharedPreferencesUtil util = SharedPreferencesUtil.getInstance(this);
            formId = util.getLong(USER_MEMBERID_KEY);
        }

        params.put("formId", formId.toString());
        ProgressDialog progress = getProgress();
        progress.show();
        sysBasePresenter.uploadFile(params, file, (long cur, long total) -> {
            progress.setMax((int)total);
            progress.setProgress((int)cur);
            Log.i(TAG, String.format("上传进度：{current: %d KB, total: %d KB}", cur, total));
            if (cur >= total) {
                progress.dismiss();
                runOnUiThread(() -> Toast.makeText(UserCenterActivity.this, "上传成功", Toast.LENGTH_LONG).show());
            }
        });
    }

    private ProgressDialog getProgress() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); // 水平进度条
        }
        return progressDialog;
    }

}